// index.js

const express = require('express'),
    body_parser = require('body-parser'),
    fs = require('fs'),
    proxy = require('http-proxy-middleware');
const options = {
    target: 'http://m.kugou.com', // 目标服务器 host
    changeOrigin: true, // 默认false，是否需要改变原始主机头为目标URL
    ws: true,
    pathRewrite: {
        '^/kugou/recommend': 'plist/list/125033',
        '^/kugou/search': '/api/v3/search/song',
        '^/kugou/music': '/app/i/getSongInfo.php',
        '^/kugou/lyrics': '/app/i/krc.php',
        '^/kugou/latest': 'rank/list',
        '^/kugou/detail': 'rank/info'
    },
    router: {
        '172.16.0.178:3000/kugou/banner': 'http://ads.service.kugou.com',
        '172.16.0.178:3000/kugou/search': 'http://mobilecdn.kugou.com'
    }
};

const app = express();

app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Credentials", true);
    res.header("Access-Control-Allow-Headers", "Connection, Content-Length, Content-Type, Date, ETag, Server, set-cookie, X-Powered-By");
    res.header("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS");
    next();
});

app.use(body_parser.urlencoded({
    extended: true
}));
app.use(body_parser.json());

/*
   @轮询 - http://ads.service.kugou.com/v1/mobile_fmbanner?&appid=1&clientver=1&clienttime=1&key=1
   @推荐 - http://m.kugou.com/plist/index?page=1&json=true
   @推荐详情 - http://m.kugou.com/plist/list/528822/?json=ture
   @搜索 - http://mobilecdn.kugou.com/api/v3/search/song?keyword=%E6%83%85%E6%AD%8C&page=1
   @歌曲地址 - http://m.kugou.com/app/i/getSongInfo.php?cmd=playInfo&hash=40AB23F48490D202EF79B2682AA1E69D&from=mkugou
   @歌词地址 - http://m.kugou.com/app/i/krc.php?cmd=100&hash=40AB23F48490D202EF79B2682AA1E69D&timelength=266000
*/
let exampleProxy = proxy(options);

app.use('/kugou/recommend', exampleProxy); // 推荐
app.use('/kugou/search', exampleProxy); // 搜索
app.use('/kugou/music', exampleProxy); // 歌曲
app.use('/kugou/lyrics', exampleProxy); // 歌词
app.use('/kugou/latest',exampleProxy); // 最新歌单
app.use('/kugou/detail',exampleProxy); // 最新歌单列表

let fileArr = fs.readdirSync(__dirname.replace('loads', 'routes'));
console.log(fileArr);

for (let i = 0; i < fileArr.length; i++) {

    let fileName1 = fileArr[i]; //包括api名,包括扩展名      api_truck.js
    let fileName2 = fileName1.split('.')[0]; //包括api名,不包括扩展名    api_truck
    let fileName3 = fileName2.split('api_')[1]; //不包括api名,            truck
    if (fileName3 && fileName2) app.use('/api/' + fileName3, require('../routes/' + fileName2)(app, express));
}

app.listen(3333, function () {
    console.log('Node Server .....');
});
